package cn.gcjxsc.service.integral;

import cn.gcjxsc.common.consts.OrderDiscr;
import cn.gcjxsc.common.consts.OrderStatus;
import cn.gcjxsc.common.consts.PayStatus;
import cn.gcjxsc.consts.IntegralRecordType;

import cn.gcjxsc.entity.mall.BaseOrder;
import cn.gcjxsc.entity.mall.ShoppingOrderExt;
import cn.gcjxsc.entity.salesman.*;
import cn.gcjxsc.repository.salesaman.SalesmanRecMemberStaticsRepository;
import cn.gcjxsc.repository.salesaman.SalesmanShoppingOrderFlagRepository;
import cn.gcjxsc.service.mall.OrderService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;

/**
 * @author pumbaa
 * @since 1.0
 */
@Service
public class IncomeService {

    public static class RemarkConst {
        public static final String SHOPPING_INCOME = "推荐会员购物,获得收益";
    }

    public static class BindingResult {
        protected String msg;
        protected int errorCount;

        public String getMsg() {
            return msg;
        }

        public int getErrorCount() {
            return errorCount;
        }
    }

    private Logger logger = LoggerFactory.getLogger(IncomeService.class);
    @Autowired
    private OrderService orderService;
    @Autowired
    private RecommendMemberService recommendMemberService;
    @Autowired
    private IntegralRecordService recordService;
    @Autowired
    private SalesmanAccountService accountService;
    @Autowired
    private SalesmanStoreStaticsService staticsService;
    @Autowired
    private SalesmanShoppingOrderFlagRepository flagRepository;
    @Autowired
    private SalesmanRecMemberStaticsRepository salesmanRecMemberStaticsRepository;

    /**
     * 检查是否为有效购物订单
     *
     * @param order         订单信息
     * @param bindingResult 检验结果
     */
    public void checkOrder(BaseOrder order, BindingResult bindingResult) {
        if (null == order) {
            bindingResult.msg = "订单不能为空";
            bindingResult.errorCount++;
        } else if (order.getDiscr() != OrderDiscr.SHOPPING_ORDER) {
            bindingResult.msg = "非购物订单";
            bindingResult.errorCount++;
        } else if (order.getPayStatus() != PayStatus.PAID) {
            bindingResult.msg = "非[支付]状态订单";
            bindingResult.errorCount++;
        } else if (order.getStatus() != OrderStatus.STATUS_SHIPPED) {
            bindingResult.msg = "非[发货]状态订单.";
            bindingResult.errorCount++;
        }
    }

    /**
     * 是否已计算收益
     *
     * @param sn 订单号
     * @return
     */
    public boolean isFlagged(String sn) {
        return flagRepository.findBySn(sn) != null;
    }

    /**
     * 会员购物,处理业务员收益提成.
     *
     * @param order 购物订单
     */
    @Transactional
    public void processShoppingOrderDone(BaseOrder order) {
        System.out.println("开始计算业务员收益....");
        Integer memberId = order.getOwnerId();
        ShoppingOrderExt orderExt = orderService.findExtByOrderId(order.getId());
        //查询最早绑定的业务员信息
        RecommendMember relationship = recommendMemberService.findRelationship(memberId, orderExt.getStoreId());
        System.out.println("推荐关系....");
        if (null == relationship) {
            System.out.println("找不到推荐关系....");
            logger.info("找不到推荐关系.订单号:{}. 会员id:{}", order.getSn(), memberId);
            return;
        }
        Salesman salesman = relationship.getSalesman();
        SalesmanAccount account = accountService.findBySalesman(salesman);
        System.out.println("账户....");
        //金额基数=应该支付的金额-运费.
        BigDecimal baseAmount = order.getPayAmount().subtract(orderExt.getExpressAmount());
        //业务员收益
        BigDecimal income = baseAmount.multiply(salesman.getRatio());
        System.out.println("收益...."+income);
        //收益流水
        IntegralRecord integralRecord = new IntegralRecord();
        integralRecord.setMemberId(salesman.getMemberId());
        integralRecord.setSalesman(salesman);
        integralRecord.setAmount(income);
        integralRecord.setCreated(orderExt.getShipTime());
        integralRecord.setSn(order.getSn());
        integralRecord.setRemark(RemarkConst.SHOPPING_INCOME);
        integralRecord.setType(IntegralRecordType.SHOPPING);
        integralRecord.setStoreId(salesman.getStoreId());
        integralRecord.setSourceAmount(baseAmount);
        integralRecord.setRate(salesman.getRatio());
        integralRecord.setStoreId(orderExt.getStoreId());
        integralRecord.setSource(memberId + "");

        //余额
        account.setBalance(account.getBalance().add(income));
        account.setTotalIncome(account.getTotalIncome().add(income));

        //处理标识
        SalesmanShoppingOrderFlag flag = new SalesmanShoppingOrderFlag();
        flag.setSn(order.getSn());
        flag.setCreated(System.currentTimeMillis() / 1000);

        //业务员店铺汇总
        SalesmanStoreStatics statics = staticsService.findBySalesmanId(salesman.getId());
        System.out.println("汇总...." + (statics == null));
        if (null == statics) {
            statics = new SalesmanStoreStatics();
            statics.setStoreId(salesman.getStoreId());
            statics.setSalesmanMemberId(salesman.getMemberId());
            statics.setSalesmanId(salesman.getId());
        }
        statics.setAmount(statics.getAmount().add(income));

        //业务员与被推荐会员汇总
        SalesmanRecMemberStatics recMemberStatics = salesmanRecMemberStaticsRepository.findBySalesmanMemberIdAndMemberIdAndStoreId(salesman.getMemberId(), memberId, salesman.getStoreId());
        System.out.println("业务员与被推荐会员汇总...." + (recMemberStatics==null));
        if (null == recMemberStatics) {
            recMemberStatics = new SalesmanRecMemberStatics();
            recMemberStatics.setSalesmanMemberId(salesman.getMemberId());
            recMemberStatics.setMemberId(memberId);
            recMemberStatics.setAmount(BigDecimal.ZERO);
            recMemberStatics.setStoreId(salesman.getStoreId());
        }
        recMemberStatics.setAmount(recMemberStatics.getAmount().add(income));
        salesmanRecMemberStaticsRepository.save(recMemberStatics);

        recordService.saveRecord(integralRecord);
        accountService.saveAccount(account);
        flagRepository.save(flag);
        staticsService.saveOrUpdateStatics(statics);
        System.out.println("计算结束....");
    }
}
